<?php

namespace common\libs\WeOpenDeveloper;

use common\models\CircuitAddress;
use common\models\OpenCity;
use common\models\PointTime;
use common\models\Site;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Exceptions\LocalCacheException;
use yii\db\Expression;

include_once __DIR__ . '/include.php';

class WechatOpen
{
    public $config;
    public $aliconfig;

    public $OauthApi;

    function __construct()
    {
        $config = \Yii::$app->params['wechat']['open'];
        $aliconfig = \Yii::$app->params['alipay'];
        /*$config['GetAccessTokenCallback'] = function ($authorizer_appid) use ($config) {
            $oauth = new \WeChat\Oauth($config);
            $refreshToken = \Cm::$db->field("select refresh_token from wechat_app where appid='{$authorizer_appid}'", "refresh_token", "");
            $result = $oauth->refreshAccessToken($authorizer_appid, $refreshToken);
            if (empty($result['authorizer_access_token'])) {
                throw new \WeChat\Exceptions\InvalidResponseException($result['errmsg'], '0');
            }
            return "";
        };*/
        $this->config = $config;
        $this->aliconfig = $aliconfig;

        $this->OauthApi = new \WeChat\Oauth($config);

        $this->OrderApi = new \WePay\Order($config);

        $this->RefundApi = new \WePay\Refund($config);

        $this->TemplateApi = new \WeChat\Template($config);

        $this->UserApi = new \WeChat\User($config);
    }

    function pay($appid)
    {
        include_once __DIR__ . '/wechat.pay.php';
        return new WechatPay($this->config);
    }

    function alipay($config,$goods)
    {
        $pay = new \AliPay\Wap($config); 
        $result = $pay->apply($goods);
        return $result;
    }

    function alinotify($config){
        $pay = new \AliPay\Wap($config); 
        $result = $pay->notify();
        return $result;    
    }

    function alirefund($config,$goods){
        $pay = \AliPay\Wap::instance($config);
        $result = $pay->refund($goods['out_trade_no'], $goods['refund_amount']);
        return $result;
    }

    function sendTemplate($type,$data){

        $sms = \Cm::$sms->aliyun();
        if($type == 'change'){
            $oldorder = \Cm::$db->one("SELECT order_number FROM `order` WHERE id={$data['old_order_id']}");
            $neworder = \Cm::$db->one("SELECT a.order_number,a.shift_id,a.circuit_id,b.departuretime,sa.name AS sitesname,sb.name AS siteename,a.user_telephone,a.p_id,a.s_id,a.e_id 
                                        FROM `order` a 
                                        LEFT JOIN shift b ON a.shift_id=b.id 
                                        LEFT JOIN circuit c  ON a.circuit_id=c.id 
                                        LEFT JOIN site sa ON sa.id=c.site_sid 
                                        LEFT JOIN site sb ON sb.id=c.site_eid  
                                        WHERE a.id={$data['changeid']} AND b.status=1 AND c.status=1 AND sa.status=1 AND sb.status=1");
            if(empty($neworder)){
                \Cm::$app->log->common("wechat-template", ['data' => $data, 'error' => '未找到订单']);
                return false;
            }
            $departuretime=PointTime::find()->andWhere(['id'=>$neworder['p_id']])->select(['departuretime'])->scalar()??0;
            if(strtotime($departuretime)>strtotime($neworder['departuretime'])){
                $neworder['departuretime']=$departuretime;
            }
            $site_data=CircuitAddress::find()->alias('ca')
                ->leftJoin(['s'=>Site::tableName()],['ca.site_id'=>new Expression('s.id')])
                ->andWhere(['ca.id'=>[$neworder['s_id'],$neworder['e_id']]])
                ->select(['s.name','ca.id'])
                ->indexBy('id')
                ->column();

            /*短信*/
            $sitename = ($site_data[$neworder['s_id']]??$neworder['sitesname'])." - ".($site_data[$neworder['e_id']]??$neworder['siteename']);

            $departuretime= date("Y年m月d日 H:i",strtotime($neworder['departuretime']));
            $orderstr = 'M'.$neworder['circuit_id'].$neworder['shift_id'];
            $res = $sms->authCode->send($neworder['user_telephone'],$type,[
                'oldorder'=>$oldorder['order_number'],
                'neworder' => $neworder['order_number'],
                'sitename' => $sitename,
                'time'=>$departuretime,
                'orderstr'=>$orderstr
            ]);

            $isok = $this->UserApi->getUserInfo($data['openid']);
            if($isok['subscribe'] == 0){
                $data['typestr'] = $type;
                \Cm::$app->log->common("wechat-template", ['data' => $data, 'error' => '未关注']);
                return false;
            }

            $tempData['template_id'] = 'aZOdHKRzLNZA-Y0f1N4D9Z9JjWTielKgeO-rD2BkiSs';
            $tempData['touser'] = $data['openid'];
            $tempData['topcolor'] = '#FF0000';

            $tempData['data']['first']['value'] = "您好,您的订单【".$oldorder['order_number']."】已成功改签,改签后信息如下：";
            $tempData['data']['first']['color'] = '#173177';
            $tempData['data']['keyword1']['value'] = $neworder['order_number'];
            $tempData['data']['keyword1']['color'] = '#173177';
            $tempData['data']['keyword2']['value'] = $sitename;
            $tempData['data']['keyword2']['color'] = '#173177';
            $tempData['data']['keyword3']['value'] = $departuretime;
            $tempData['data']['keyword3']['color'] = '#173177';
            $tempData['data']['keyword4']['value'] = $orderstr;
            $tempData['data']['keyword4']['color'] = '#173177';
            $tempData['data']['remark']['value'] = "如有疑问，请咨询0827-5233429。";
            $tempData['data']['remark']['color'] = '#173177';
        }elseif ($type == 'order') {
            $info = \Cm::$db->one("SELECT a.order_number,a.order_price,a.ridership,b.departuretime,sa.name AS sitesname,sb.name AS siteename,c.s_address,c.e_address,c.name,a.user_telephone,a.p_id,a.s_id,a.e_id 
                                        FROM `order` a 
                                        LEFT JOIN shift b ON a.shift_id=b.id 
                                        LEFT JOIN circuit c  ON a.circuit_id=c.id 
                                        LEFT JOIN site sa ON sa.id=c.site_sid 
                                        LEFT JOIN site sb ON sb.id=c.site_eid  
                                        WHERE a.id={$data['order_id']} AND b.status=1 AND c.status=1 AND sa.status=1 AND sb.status=1");
            if(empty($info)){
                \Cm::$app->log->common("wechat-template", ['data' => $data, 'error' => '未找到订单']);
                return false;
            }

            $site_data=CircuitAddress::find()->alias('ca')
                ->leftJoin(['s'=>Site::tableName()],['ca.site_id'=>new Expression('s.id')])
                ->andWhere(['ca.id'=>[$info['s_id'],$info['e_id']]])
                ->select(['s.name','ca.address','ca.id'])
                ->indexBy('id')
                ->asArray()
                ->all();
            $sname =  !empty($site_data[$info['s_id']])?($site_data[$info['s_id']]['address']??$site_data[$info['s_id']]['name']) : ($info['s_address']??$info['sitesname']);
            $ename =  !empty($site_data[$info['e_id']])?($site_data[$info['e_id']]['address']??$site_data[$info['e_id']]['name']) : ($info['e_address']??$info['siteename']);

            $departuretime=PointTime::find()->andWhere(['id'=>$info['p_id']])->select(['departuretime'])->scalar()??0;
            if(strtotime($departuretime)>strtotime($info['departuretime'])){
                $info['departuretime']=$departuretime;
            }
            /*短信*/
            $departuretime = date("Y年m月d日 H:i",strtotime($info['departuretime']));
            $res = $sms->authCode->send($info['user_telephone'],$type,[
                'circuitname'=>$info['name'],
                'ordernumber' => $info['order_number'],
                'orderprice' => $info['order_price'],
                'ticketnum'=>$info['ridership'],
                'saddress'=>$sname,
                'eaddress'=>$ename,
                'time' => $departuretime
            ]);

            $isok = $this->UserApi->getUserInfo($data['openid']);
            if($isok['subscribe'] == 0){
                $data['typestr'] = $type;
                \Cm::$app->log->common("wechat-template", ['data' => $data, 'error' => '未关注']);
                return false;
            }

            $tempData['template_id'] = 'b7hCgevG11weDYdLKw7DcAB834hJ93NA9rth7_YALZk';
            $tempData['touser'] = $data['openid'];
            $tempData['topcolor'] = '#FF0000';

            $tempData['data']['first']['value'] = "您好,您已成功预订".$info['name']."的出行行程,车票信息如下：";
            $tempData['data']['first']['color'] = '#173177';
            $tempData['data']['keyword1']['value'] = $info['order_number'];
            $tempData['data']['keyword1']['color'] = '#173177';
            $tempData['data']['keyword2']['value'] = "￥".$info['order_price']."（".$info['ridership']."张）";
            $tempData['data']['keyword2']['color'] = '#173177';
            $tempData['data']['keyword3']['value'] = $sname;
            $tempData['data']['keyword3']['color'] = '#173177';
            $tempData['data']['keyword4']['value'] = $ename;
            $tempData['data']['keyword4']['color'] = '#173177';
            $tempData['data']['keyword5']['value'] = $departuretime;
            $tempData['data']['keyword5']['color'] = '#173177';
            $tempData['data']['remark']['value'] = "如有疑问，请咨询0827-5233429。祝您旅途愉快！";
            $tempData['data']['remark']['color'] = '#173177';
        }elseif ($type == 'refund') {
            $info = \Cm::$db->one("SELECT a.order_number,a.p_id,a.order_price,a.refund_amount,a.refund_service,ur.openid,b.departuretime,sa.name AS sitesname,sb.name AS siteename,a.user_telephone,c.name as circuitname 
                                    FROM `order` a 
                                    LEFT JOIN user ur ON a.user_id=ur.id
                                    LEFT JOIN shift b ON a.shift_id=b.id 
                                    LEFT JOIN circuit c  ON a.circuit_id=c.id 
                                    LEFT JOIN site sa ON sa.id=c.site_sid 
                                    LEFT JOIN site sb ON sb.id=c.site_eid 
                                    WHERE a.id={$data['order_id']} AND b.status=1 AND c.status=1 AND sa.status=1 AND sb.status=1");
            if(empty($info)){
                \Cm::$app->log->common("wechat-template", ['data' => $data, 'error' => '未找到订单']);
                return false;
            }
            $departuretime=PointTime::find()->andWhere(['id'=>$info['p_id']])->select(['departuretime'])->scalar()??0;
            if(strtotime($departuretime)>strtotime($info['departuretime'])){
                $info['departuretime']=$departuretime;
            }
            $time = date("H:i",strtotime($info['departuretime']));
            $day = date("Y年m月d日",strtotime($info['departuretime']));
            /*短信*/
            $res = $sms->authCode->send($info['user_telephone'],$type,[
                'circuit'=>$info['circuitname'],
                'order' => $info['order_number'],
                'day'=>$day,
                'time' => $time
            ]);

            $isok = $this->UserApi->getUserInfo($info['openid']);
            if($isok['subscribe'] == 0){
                $data['typestr'] = $type;
                \Cm::$app->log->common("wechat-template", ['data' => $data, 'error' => '未关注']);
                return false;
            }

            /*$tempData['template_id'] = 'KEoCeSZyljK5QtPp9UMw1qOHvoIj0cc4XC-zDk5g-sU';
            $tempData['touser'] = $info['openid'];
            $tempData['topcolor'] = '#FF0000';

            $tempData['data']['first']['value'] = "您好,您的【".$info['order_number']."】订单已成功退票：";
            $tempData['data']['first']['color'] = '#173177';
            $tempData['data']['keyword1']['value'] = $info['sitesname']."-".$info['siteename'];
            $tempData['data']['keyword1']['color'] = '#173177';
            $tempData['data']['keyword2']['value'] = $time;
            $tempData['data']['keyword2']['color'] = '#173177';
            $tempData['data']['keyword3']['value'] = $day;
            $tempData['data']['keyword3']['color'] = '#173177';
            $tempData['data']['remark']['value'] = "如有疑问，请咨询0827-5233429。";
            $tempData['data']['remark']['color'] = '#173177';*/
            $tempData['template_id'] = 'R5afomXjaDmYGCeJgunGxEKt3MZqznd2tt9teJYysSI';
            $tempData['touser'] = $info['openid'];
            $tempData['topcolor'] = '#FF0000';

            $tempData['data']['first']['value'] = "您好,您预约班车退票成功，退票金额将退还到你支付账户，请确认查收！您的退票情况如下：";
            $tempData['data']['first']['color'] = '#173177';
            $tempData['data']['keyword1']['value'] = $info['circuitname'];
            $tempData['data']['keyword1']['color'] = '#173177';
            $tempData['data']['keyword2']['value'] = $info['user_telephone'];
            $tempData['data']['keyword2']['color'] = '#173177';
            $tempData['data']['keyword3']['value'] = $time;
            $tempData['data']['keyword3']['color'] = '#173177';
            $tempData['data']['keyword4']['value'] = $day;
            $tempData['data']['keyword4']['color'] = '#173177';
            $tempData['data']['keyword5']['value'] = $info['refund_amount'];
            $tempData['data']['keyword5']['color'] = '#173177';
            $tempData['data']['remark']['value'] = "按退票规则：需收取手续费".$info['refund_service']."元，退还金额".$info['refund_amount']."元。\r\n备注：如有疑问，请咨询0827-5233429，欢迎您再次选择奚若旅游。";
            $tempData['data']['remark']['color'] = '#173177';
        }elseif ($type == 'refund2') {
            $info = \Cm::$db->one("SELECT a.order_number,a.ridership,a.order_price,a.refund_amount,a.p_id,ur.openid,b.departuretime,sa.name AS sitesname,sb.name AS siteename,a.user_telephone,c.name as circuitname 
                                    FROM `order` a 
                                    LEFT JOIN user ur ON a.user_id=ur.id
                                    LEFT JOIN shift b ON a.shift_id=b.id 
                                    LEFT JOIN circuit c  ON a.circuit_id=c.id 
                                    LEFT JOIN site sa ON sa.id=c.site_sid 
                                    LEFT JOIN site sb ON sb.id=c.site_eid 
                                    WHERE a.id={$data['order_id']} AND b.status=1 AND c.status=1 AND sa.status=1 AND sb.status=1");
            if(empty($info)){
                \Cm::$app->log->common("wechat-template", ['data' => $data, 'error' => '未找到订单']);
                return false;
            }
            $departuretime=PointTime::find()->andWhere(['id'=>$info['p_id']])->select(['departuretime'])->scalar()??0;
            if(strtotime($departuretime)>strtotime($info['departuretime'])){
                $info['departuretime']=$departuretime;
            }
            $time = date("H:i",strtotime($info['departuretime']));
            $day = date("Y年m月d日",strtotime($info['departuretime']));
            /*短信*/
            $res = $sms->authCode->send($info['user_telephone'],$type,[
                'circuit'=>$info['circuitname'],
                'order' => $info['order_number'],
                'day'=>$day,
                'time' => $time
            ]);

            $isok = $this->UserApi->getUserInfo($info['openid']);
            if($isok['subscribe'] == 0){
                $data['typestr'] = $type;
                \Cm::$app->log->common("wechat-template", ['data' => $data, 'error' => '未关注']);
                return false;
            }

            $tempData['template_id'] = 'mBNShC_dU4eBpKF0rUfKEoC7BqGPMMy9317Y8JgHu1U';
            $tempData['touser'] = $info['openid'];
            $tempData['topcolor'] = '#FF0000';

            $tempData['data']['first']['value'] = "亲，很抱歉！您订购的".$info['ridership']."张车票取消发车了。";
            $tempData['data']['first']['color'] = '#173177';
            $tempData['data']['keyword1']['value'] = $info['refund_amount'];
            $tempData['data']['keyword1']['color'] = '#173177';
            $tempData['data']['keyword2']['value'] = $info['order_price'];
            $tempData['data']['keyword2']['color'] = '#173177';
            $tempData['data']['keyword3']['value'] = $info['circuitname'];
            $tempData['data']['keyword3']['color'] = '#173177';
            $tempData['data']['keyword4']['value'] = $info['departuretime'];
            $tempData['data']['keyword4']['color'] = '#173177';
            $tempData['data']['keyword5']['value'] = '0827-5233429';
            $tempData['data']['keyword5']['color'] = '#173177';
            $tempData['data']['remark']['value'] = "经此线路开发商确认，由于此班次购票人数较少达不到发车要求，导致不能正常发车，请您改用其他出行方式。给您造成的不便深感抱歉！";
            $tempData['data']['remark']['color'] = '#173177';
        }elseif ($type == "sendcar") {
            foreach ($data['order'] as $key => $value) {
                $info = \Cm::$db->one("SELECT a.order_number,a.p_id,a.s_id,a.e_id,ur.openid,b.addtime,sa.name AS sitesname,sb.name AS siteename,cr.plate,(SELECT GROUP_CONCAT(seat_number) AS seat_number FROM order_passenger WHERE order_id=a.id) AS seat_number,b.departuretime,a.user_telephone
                                    FROM `order` a 
                                    LEFT JOIN user ur ON a.user_id=ur.id
                                    LEFT JOIN shift b ON a.shift_id=b.id 
                                    LEFT JOIN circuit c  ON a.circuit_id=c.id 
                                    LEFT JOIN site sa ON sa.id=c.site_sid 
                                    LEFT JOIN site sb ON sb.id=c.site_eid 
                                    LEFT JOIN order_car oc ON oc.order_id=a.id
                                    LEFT JOIN car cr ON cr.id=oc.car_id
                                    WHERE a.id={$value} AND b.status=1 AND c.status=1 AND sa.status=1 AND sb.status=1");
                if(empty($info)){
                    \Cm::$app->log->common("wechat-template", ['data' => $value, 'error' => '未找到订单']);
                    continue;
                }

                $site_data=CircuitAddress::find()->alias('ca')
                    ->leftJoin(['s'=>Site::tableName()],['ca.site_id'=>new Expression('s.id')])
                    ->andWhere(['ca.id'=>[$info['s_id'],$info['e_id']]])
                    ->select(['s.name','ca.address','ca.id'])
                    ->indexBy('id')
                    ->asArray()
                    ->all();
                $sname =  !empty($site_data[$info['s_id']])?$site_data[$info['s_id']]['name'] : $info['sitesname'];
                $ename =  !empty($site_data[$info['e_id']])?$site_data[$info['e_id']]['name'] : $info['siteename'];

                $departuretime=PointTime::find()->andWhere(['id'=>$info['p_id']])->select(['departuretime'])->scalar()??0;
                if(strtotime($departuretime)>strtotime($info['departuretime'])){
                    $info['departuretime']=$departuretime;
                }
                $info['seat_number'] = empty($info['seat_number']) ? '' : implode("、", explode(",", $info['seat_number']));
                $time = date("Y-m-d H:i",strtotime($info['departuretime']));
                /*短信*/
                $res = $sms->authCode->send($info['user_telephone'],$type,[
                    'sitename'=>$sname."-".$ename,
                    'order' => $info['order_number'],
                    'plate'=>$info['plate'],
                    'time' => $time,
                    'seatnumber'=>empty($info['seat_number']) ? '' : $info['seat_number']."号"
                ]);

                $isok = $this->UserApi->getUserInfo($info['openid']);
                if($isok['subscribe'] == 0){
                    $info['typestr'] = $type;
                    \Cm::$app->log->common("wechat-template", ['data' => $info, 'error' => '未关注']);
                    return false;
                }else{
                    $remark = "";
                    $remark .= empty($info['seat_number']) ? '' : '您的乘车座位为：'.$info['seat_number'].'号。';
                    $remark .= "如有疑问，请咨询0827-5233429。";
                    $tempData['template_id'] = 'dypT1Hhk4IY3xuSjNKFzJdkyLUqWeD3HVPWGxbzrE94';
                    $tempData['touser'] = $info['openid'];
                    $tempData['topcolor'] = '#FF0000';

                    $tempData['data']['first']['value'] = "尊敬的用户,您好";
                    $tempData['data']['first']['color'] = '#173177';
                    $tempData['data']['keyword1']['value'] = $info['order_number'];
                    $tempData['data']['keyword1']['color'] = '#173177';
                    $tempData['data']['keyword2']['value'] = $sname."-".$ename;
                    $tempData['data']['keyword2']['color'] = '#173177';
                    $tempData['data']['keyword3']['value'] = $time;
                    $tempData['data']['keyword3']['color'] = '#173177';
                    $tempData['data']['keyword4']['value'] = $info['plate'];
                    $tempData['data']['keyword4']['color'] = '#173177';
                    $tempData['data']['remark']['value'] = $remark;
                    $tempData['data']['remark']['color'] = '#173177';
                    $res = $this->TemplateApi->send($tempData);
                    if(!$res){
                        \Cm::$app->log->common("wechat-template", ['data' => $tempData, 'error' => '发送失败']);
                    }
                }    
            }

            return true;
        }elseif ($type == 'carpool') {
            foreach ($data['order'] as $key => $value) {
                $info = \Cm::$db->one("SELECT a.order_number,a.p_id,a.s_id,a.e_id,ur.openid,cr.plate,(SELECT GROUP_CONCAT(seat_number) AS seat_number FROM order_passenger WHERE order_id=a.id) AS seat_number,a.user_telephone,b.departuretime,sa.name AS sitesname,sb.name AS siteename
                                    FROM `order` a 
                                    LEFT JOIN user ur ON a.user_id=ur.id
                                    LEFT JOIN order_car oc ON oc.order_id=a.id
                                    LEFT JOIN car cr ON cr.id=oc.car_id
                                    LEFT JOIN shift b ON a.shift_id=b.id 
                                    LEFT JOIN circuit c  ON a.circuit_id=c.id 
                                    LEFT JOIN site sa ON sa.id=c.site_sid 
                                    LEFT JOIN site sb ON sb.id=c.site_eid 
                                    WHERE a.id={$value} AND b.status=1 AND c.status=1 AND sa.status=1 AND sb.status=1");
                if(empty($info)){
                    \Cm::$app->log->common("wechat-template", ['data' => $value, 'error' => '未找到订单']);
                    continue;
                }
                $site_data=CircuitAddress::find()->alias('ca')
                    ->leftJoin(['s'=>Site::tableName()],['ca.site_id'=>new Expression('s.id')])
                    ->andWhere(['ca.id'=>[$info['s_id'],$info['e_id']]])
                    ->select(['s.name','ca.address','ca.id'])
                    ->indexBy('id')
                    ->asArray()
                    ->all();
                $sname =  !empty($site_data[$info['s_id']])?$site_data[$info['s_id']]['name'] : $info['sitesname'];
                $ename =  !empty($site_data[$info['e_id']])?$site_data[$info['e_id']]['name'] : $info['siteename'];
                $info['seat_number'] = empty($info['seat_number']) ? '' : implode("、", explode(",", $info['seat_number']));
                $departuretime=PointTime::find()->andWhere(['id'=>$info['p_id']])->select(['departuretime'])->scalar()??0;
                if(strtotime($departuretime)>strtotime($info['departuretime'])){
                    $info['departuretime']=$departuretime;
                }
                $time = date("Y-m-d H:i",strtotime($info['departuretime']));
                /*短信*/
                $res = $sms->authCode->send($info['user_telephone'],$type,[
                    'sitename'=>$sname."-".$ename,
                    'order' => $info['order_number'],
                    'plate'=>$info['plate'],
                    'time' => $time,
                    'seatnumber'=>empty($info['seat_number']) ? '' : $info['seat_number']."号"
                ]);
                $isok = $this->UserApi->getUserInfo($info['openid']);
                if($isok['subscribe'] == 0){
                    $info['typestr'] = $type;
                    \Cm::$app->log->common("wechat-template", ['data' => $info, 'error' => '未关注']);
                    return false;
                }else{
                    $html = "您将搭乘车辆的车牌将换成：".$info['plate'].",您的乘车座位为：".$info['seat_number'].'号。';
                    $tempData['template_id'] = '1peLoX8uvYfWheCHhCzTljkojYmchT2L9pkqAmJx2O8';
                    $tempData['touser'] = $info['openid'];
                    $tempData['topcolor'] = '#FF0000';
                    $tempData['data']['first']['value'] = "尊敬的用户,您好订单行程信息有变更：";
                    $tempData['data']['first']['color'] = '#173177';
                    $tempData['data']['keyword1']['value'] = $info['order_number'];
                    $tempData['data']['keyword1']['color'] = '#173177';
                    $tempData['data']['keyword2']['value'] = $html;
                    $tempData['data']['keyword2']['color'] = '#173177';
                    $tempData['data']['remark']['value'] = "如有疑问，请咨询0827-5233429。";
                    $tempData['data']['remark']['color'] = '#173177';
                    $res = $this->TemplateApi->send($tempData);
                    if(!$res){
                        \Cm::$app->log->common("wechat-template", ['data' => $tempData, 'error' => '发送失败']);
                    }
                }    
            }
            return true;
        }elseif ($type == 'notice') { 
            foreach ($data['order'] as $key => $value) {
                $info = \Cm::$db->one("SELECT a.order_number,ur.openid,a.user_telephone,a.p_id
                                    FROM `order` a 
                                    LEFT JOIN user ur ON a.user_id=ur.id
                                    WHERE a.id={$value}");
                if(empty($info)){
                    \Cm::$app->log->common("wechat-template", ['data' => $value, 'error' => '未找到订单']);
                    continue;
                }
                $departuretime=PointTime::find()->andWhere(['id'=>$info['p_id']])->select(['departuretime'])->scalar()??0;
                if(strtotime($departuretime)>strtotime($data['departuretime'])){
                    $data['departuretime']=$departuretime;
                }
                /*短信*/
                $res = $sms->authCode->send($info['user_telephone'],$type,[
                    'address'=>$data['address'],
                    'order' => $info['order_number'],
                    'plate'=>$data['plate'],
                    'time' => date("Y年m月d",strtotime($data['departuretime'])),
                    'time2'=> date("H:i",strtotime($data['departuretime'])),
                    'username' => $data['name'],
                    'tel' => $data['telephone']
                ]);
                $isok = $this->UserApi->getUserInfo($info['openid']);
                if($isok['subscribe'] == 0){
                    $info['typestr'] = $type;
                    \Cm::$app->log->common("wechat-template", ['data' => $info, 'error' => '未关注']);
                    return false;
                }else{
                    $html = "我们将上车地址改在".$data['address'].",请注意车牌号为：".$data['plate'].",发车时间为：".$data['departuretime'].",联系人：".$data['name'].",联系电话：".$data['telephone'].",请按时到达，谢谢配合";
                    $tempData['template_id'] = '1peLoX8uvYfWheCHhCzTljkojYmchT2L9pkqAmJx2O8';
                    $tempData['touser'] = $info['openid'];
                    $tempData['topcolor'] = '#FF0000';
                    $tempData['data']['first']['value'] = "尊敬的用户,您好订单行程信息有变更：";
                    $tempData['data']['first']['color'] = '#173177';
                    $tempData['data']['keyword1']['value'] = $info['order_number'];
                    $tempData['data']['keyword1']['color'] = '#173177';
                    $tempData['data']['keyword2']['value'] = $html;
                    $tempData['data']['keyword2']['color'] = '#173177';
                    $tempData['data']['remark']['value'] = "如有疑问，请咨询0827-5233429。";
                    $tempData['data']['remark']['color'] = '#173177';
                    $res = $this->TemplateApi->send($tempData);
                    if(!$res){
                        \Cm::$app->log->common("wechat-template", ['data' => $tempData, 'error' => '发送失败']);
                    }
                }    
            }
            return true;
        }
        $error = '';
        try {
            $res = $this->TemplateApi->send($tempData);
            if ($res){
                return true;
            }else{
                $error = '发送失败';
            }
        } catch (InvalidResponseException $e) {
            $error = $e->getMessage();
        } catch (LocalCacheException $e) {
            $error .= $e->getMessage();
        } catch (\Exception $e) {
            $error .= $e->getMessage();
        }

        if (!empty($error)){
            \Cm::$app->log->common("wechat-template", ['data' => $tempData, 'error' => $error]);
            return false;
        }
    }
}